package com.yc.vote.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yc.vote.bean.UserInfo;
import com.yc.vote.service.IUserInfoService;
import com.yc.vote.service.impl.UserInfoServiceImpl;
import com.yc.vote.util.RequestParamUtil;

/**
 * 用户信息控制层
 * @author 3456
 * Company 源辰
 * @date 2023年3月17日
 */
@WebServlet("/user/*")
public class UserInfoController extends BaseController{

	private static final long serialVersionUID = -7178728513794494844L;

	/**
	 *  用户登录
	 * /user/login
	 * @param request
	 * @param response
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException, IllegalAccessException{
		UserInfo uf = RequestParamUtil.getParams(request, UserInfo.class);
		ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		IUserInfoService userInfoService = (IUserInfoService) context.getBean("userInfoServiceImpl");
		UserInfo user = userInfoService.login(uf);
		if(user == null) {
			this.send(response, 500, "失败");
			return;
		}
		request.getSession().setAttribute("currentLoginUser", user);
		this.send(response, 200, "成功");
	}

	/**
	 *  用户注册
	 * /user/login
	 * @param request
	 * @param response
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public void reg(HttpServletRequest request, HttpServletResponse response) throws IOException{
		UserInfo uf = RequestParamUtil.getParams(request, UserInfo.class);
		ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		IUserInfoService userInfoService = (IUserInfoService) context.getBean("userInfoServiceImpl");
		
		int result = userInfoService.reg(uf);
		if(result > 0) {
			this.send(response, 200, "成功");
			return;
		}
		
		this.send(response, 500, "失败");
	}
	
	/**
	 * 检查获取当前用户信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void check(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Object obj = request.getSession().getAttribute("currentLoginUser");
		if(obj == null) {
			this.send(response, 600, "未登录");
			return;
		}
		this.send(response, 200, obj);
	}
}
